package com.zhonghui.dolo.manager.config.interceptor;

import com.zhonghui.dolo.manager.model.vo.AdminVo;
import com.zhonghui.dolo.manager.model.vo.ModuleVo;
import com.zhonghui.dolo.manager.util.Constans;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class CheckPermissionInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (!requestURI.contains(".html")) {
            return true;
        }
        // 判断用户是否登录
        AdminVo adminVo = (AdminVo) request.getSession().getAttribute("admin");
        if (adminVo == null) {
            response.sendRedirect("/");
            return false;
        }
        // 如果是总管理员角色
        if (adminVo.getRoleId() == Constans.Role.ADMIN) {
            return true;
        }
        List<ModuleVo> moduleVoList = (List<ModuleVo>) request.getSession().getAttribute("moduleVoList");
        List<String> permission = new ArrayList<>();
        for (ModuleVo moduleVo : moduleVoList) {
            for (ModuleVo.SubModuleVo subModuleVo : moduleVo.getSubModelList()) {
                permission.add(subModuleVo.getUrl());
            }
        }

        for (String url : permission) {
            // 拥有权限
            if (url.contains(requestURI)) {
                return true;
            }
        }
        response.sendRedirect("/");
        return false;
    }
}
